package mse.eai.jbpm.lotteryResultsProcess;

import java.util.Map.Entry;

import org.jboss.logging.Logger;
import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

// Sets the current data in the context and removes it from the list
public class SetCurrentWinner implements ActionHandler {

	private static final Logger log = Logger.getLogger(SetCurrentWinner.class);

	public void execute(ExecutionContext context) throws Exception {

		log.info("Executing ---------->");

		try {

			Entry<Integer, Integer>[] winnersList = (Entry<Integer, Integer>[]) context
					.getVariable("winnersList");
			
			log.info("Got from context: " + "winnersList  = " + winnersList);
			
			for (int i=0; i < winnersList.length; i++) {
				if (winnersList[i] != null) {
					Entry<Integer, Integer> winner = winnersList[i];

					//PUT DATA IN CONTEXT
					context.setVariable("uid", winner.getKey());
					context.setVariable("amount", winner.getValue());
			
					log.info("Set in context: " + "uid  = " + winner.getKey());
					log.info("Set in context: " + "amount  = " + winner.getValue());
					
					// REMOVE FROM THE LIST
					winnersList[i] = null;
					
					break;
				}
			}
						
			context.leaveNode();

		} catch (Exception ex) {
			log.error("Exception: ", ex);
			log.error("ProcessInstance will be suspended");
			context.getProcessInstance().suspend();
		}
		
		log.info("<--------------- Done");
	}

}
